/*
import { $resolve } from 'request';
 * @Author: zjj 
 * @Date: 2018-01-06 23:36:04 
 * @Last Modified by: zjj
 * @Last Modified time: 2018-02-04 15:51:33
 */
import wepy from 'wepy'
import {$getUserInfo, $login} from './login'



/**
 * 简单封装request请求
 * @param {*} url 请求地址
 * @param {*} data 发送数据
 * @param {*} isloading 是否开启加载动画 
 */
const $request = (url, data, isloading = false) => new Promise((resolve, reject) => {
  const _http = () => {
    wepy.request({
      url: 'https://sinopec.lol580.com' + url,
      data,
      header: {
        'content-type': 'application/json' // 默认值
      },
      method: 'POST',
      success(res) {
        //请求成功处理
        const {data} = res;
        if (data.success) {
          resolve(data)
        }else {
          reject(data.msg)
        }
      },
      fail(err) {
        //请求失败处理
        reject('请求发生了错误，请稍后再试～');
      },
      complete(res) {
        //请求结束出里，不管失败还是成功都会调用
        isloading && wepy.hideLoading(); 
      }
  
    })
  }
  //开启加载动画
  isloading && wepy.showLoading({title: '玩命加载中...'});
  wepy.checkSession({
    success(e) {
      if (e.errMsg === "checkSession:ok") {
        _http();
      }else {
        wx.login() //重新登录
      }
    },
    fail: function () {
       //登录态过期
       wx.login() //重新登录
    }
    
  })
  
})

const _login = (cb = () => {}) => {
  $login()
    .then(code => {
      //传送code
      $request('/api/api/OnLogin', {
        code
      }, true)
      .then(result => {
        wx.setStorageSync('sessionId', result.source);
        $getUserInfo()
        .then(userInof => {
          $request(`/api/api/CheckWxOpenSignature?sessionId=${wx.getStorageSync('sessionId')}`, {
            rawData:userInof.rawData,
            signature:userInof.signature
          })
          .then(data => {
            $getUserInfo()
            .then(userInof => {
              $request(`/api/api/DecodeEncryptedData?sessionId=${wx.getStorageSync('sessionId')}`, {
                type:"userInfo",
                encryptedData:userInof.encryptedData,
                iv:userInof.iv
              })
              .then(data => {
                cb();
              })
              .catch(err => {

              })
            })
          })
          .catch(err => {

          })
        })
        
      })
      .catch(err => {

      })
    })
    .catch(err => console.log(err)) 
}

export default $request;